import pymysql
from configuration.mysql_config import MysqlConfig

class SQLManager:

    # 连接数据库
    # 将conn,cursor作为类的属性，通过connect方法触发生成
    def __init__(self):
        self.conn = None
        self.cursor = None
        self.connect()

    def connect(self):
        self.conn = pymysql.connect(
            host=MysqlConfig.HOST,
            port=MysqlConfig.PORT,
            user=MysqlConfig.USER,
            password=MysqlConfig.PASSWORD,
            db=MysqlConfig.DB,
            charset=MysqlConfig.CHARSET
        )

        self.cursor = self.conn.cursor()

    # 查询多条数据
    def get_all(self, sql, *args):
        self.cursor.execute(sql, *args)
        return self.cursor.fetchall()

    # 查询一条数据
    def get_one(self, sql, *args):
        self.cursor.execute(sql, *args)
        return self.cursor.fetchone()

    # 修改数据
    def modify(self, sql, *args):
        # print(args)
        self.cursor.execute(sql, args)
        self.conn.commit()
    def insert_return_key(self, sql, *args):
        self.cursor.execute(sql, args)
        self.conn.commit()
        return self.get_one("select @@identity")[0]

    # 关闭数据库cursor和连接
    def close(self):
        self.cursor.close()
        self.conn.close()

    def __enter__(self):

        return self
    def __exit__(self, exc_type, exc_val, exc_tb):
        # print(exc_type,exc_val,exc_tb)
        self.close()
if __name__ == '__main__':

    with SQLManager() as db:
        # res = db.get_one("select * from test")
        # print(res)
        # print(type(res))
        res = db.modify("insert into test values(null,%s)", 1)
        print(res)